package apibasej.db.server.utilmetadata;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import apibasej.db.metadata.Tab;

/**
 * http://code.google.com/p/apibasej/
 * 
 * @author Julio Azevedo Lessa - apibasej@gmail.com
 * 
 */
public class GenModelImage {

	private String dirBaseSource;
	private String packageRoot;
	private String nameClassTabGroup;
	private LoaderModelDB loaderModelDB;
	
	
	public GenModelImage(String dirBaseSource, String packageRoot, String nameClassTabGroup, LoaderModelDB loaderModelDB) {
		this.dirBaseSource = dirBaseSource;
		this.packageRoot = packageRoot;
		this.nameClassTabGroup = nameClassTabGroup;
		this.loaderModelDB = loaderModelDB;
	}


	public void generate() throws IOException{
		File src = new File(dirBaseSource);
		src.mkdirs();
		File dirPac = new File(src,packageRoot.replaceAll("\\.","/"));
		dirPac.mkdirs();
		
		String genBy = "/**\r\n * Generated by "+GenModelImage.class.getName()+" (http://code.google.com/p/apibasej/)\r\n */\r\n";
		
		String bodyClassTabs = genBy+"package "+packageRoot+";\r\n" +
							   "\r\npublic class "+nameClassTabGroup+"{\r\n\r\n"; // extends TabGroup
		
		bodyClassTabs += "\tprivate "+nameClassTabGroup+"(){}\r\n\r\n"; // serve somente para ter as variáveis para as tabelas 
		
		for(Tab t : loaderModelDB.getTabs().values()){
			
			// se o tipo não fo Tab, significa que foi adicionado manualmente no LoaderModelDB, 
			//somente para conseguir referenciar as FKs,
			// por isso não deve gerar a classe, pois já existe em outro pacote
			if(!t.getClass().equals(Tab.class)){
				continue;
			}
			
			String tn = t.getName();
			
			bodyClassTabs += "\tpublic static final "+tn+" "+tn+" = "+packageRoot+"."+tn+".getInstance();\r\n"; //new "+tn+"()// não usar new para não ficar diferente da tab.INST
			
			File c = new File(dirPac,tn+".java");
			FileOutputStream fos = new FileOutputStream(c);
			String bodyClass = genBy+"package "+packageRoot+";\r\n"+t.getStringForClass(this.nameClassTabGroup,packageRoot);
			fos.write(bodyClass.getBytes());
			fos.close();
			
		}
		bodyClassTabs += "\r\n}";
		
		File c = new File(dirPac,nameClassTabGroup+".java");
		FileOutputStream fos = new FileOutputStream(c);
		fos.write(bodyClassTabs.getBytes());
		fos.close();
		
	}
	
	
	
	
}
